<script setup>
import { useRouter } from 'vue-router'
import { Back } from '@element-plus/icons-vue'
import {getCategoryList } from '@/api/snacks.js'
import {addSetmeal,querySetmealById,editSetmeal} from '@/api/setmeal.js'
import ImgUpload from '@/components/ImgUpload/index.vue'
import addSnacks from '@/views/setmeal/commonents/addSnacks.vue'

import {onMounted, ref} from 'vue'


const router =  useRouter()

const imageUrl = ref('') //图片
const drawer = ref(false)//弹窗
const snacksTable = ref([])//套餐零食Table 
const seachKey = ref('')
const checkList=ref([]) //选中零食列表
const setMealList = ref([])//套餐分类列表
const actionType =ref('')//请求状态
const formRef = ref()
const ruleForm = ref({
    name: '',
    categoryId: '',
    price: '',
    code: '',
    image: '',
    description: '',
    setmealSnackses: [],
    status: true,
  }
)

const rules= {
      name: {
        required: true,
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请输入套餐名称'))
          } else {
            const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
            if (!reg.test(value)) {
              callback(new Error('套餐名称输入不符，请输入2-20个字符'))
            } else {
              callback()
            }
          }
        },
        trigger: 'blur'
      },
      categoryId: {
        required: true,
        message: '请选择套餐分类',
        trigger: 'change'
      },
      image: {
        required: true,
        message: '零食图片不能为空'
      },
      price: {
        required: true,
        // 'message': '请输入套餐价格',
        validator: (rules, value, callback) => {
          const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
          if (!reg.test(value) || Number(value) <= 0) {
            callback(
              new Error(
                '套餐价格格式有误，请输入大于零且最多保留两位小数的金额'
              )
            )
          } else {
            callback()
          }
        },
        trigger: 'blur'
      },
      code: { required: true, message: '请输入商品码', trigger: 'blur' }
    }


onMounted(()=>{
  getSnacksTypeList()
  actionType.value = router.currentRoute.value.query.id ? 'update' : 'add'
  // console.log(actionType.value )
  if (actionType.value === 'update') {
    getSetmealById()
  }
})

//获取套餐分类
const getSnacksTypeList = async ()  =>{
  const res = await getCategoryList({type: 2})
// console.log(res)
if(res.data.code ===1 ){
  setMealList .value = res.data.data
}
}

//根据套餐id查询做回显
const getSetmealById = async() =>{
  const res = await querySetmealById(router.currentRoute.value.query.id)
  // console.log(res)
  if(res.data.code === 1){
    ruleForm.value=res.data.data
    imageUrl.value = ruleForm.value.image 
    snacksTable.value = res.data.data.setmealSnackses.reverse()
    checkList.value = res.data.data.setmealSnackses
  }
}


// 获取添加菜品数据 - 确定加菜倒序展示
const getCheckList =(value) => {
  // console.log(value)
    checkList.value = [...value].reverse()
  }

  // 保存添加菜品列表
  const  addTableList = ()=>{
     snacksTable.value = JSON.parse(JSON.stringify(checkList.value))
     snacksTable.value.forEach((n) => {
       n.copies = 1
     })
     drawer.value = false
  }

  //删除零食
  const delSnacksHandle =(ind)=>{
    snacksTable.value.splice(ind,1)
    checkList.value = snacksTable.value
  }

//打开弹层
const openAddSnacks =()=>{
  drawer.value = true
}

//关闭弹层
const handleClose = () => {
  drawer.value = false
}

//图片地址赋值
const imageChange = value => {
  imageUrl.value = value
  ruleForm.value.image = imageUrl.value
}


const submitForm = async (formName,st) =>{
//  console.log(snacksTable.value)
  const valid = await formRef.value.validate()
  if(valid){
    const params = {...ruleForm.value}
    params.setmealSnackses = snacksTable.value.map((obj) => ({
          copies: obj.copies,
          snacksId: obj.id,
          name: obj.name,
          price: obj.price
        }))
        
    params.status = actionType.value === 'add' ? 0 : ruleForm.value.status ? 1 : 0
    // console.log(params) // 提交表单数据
   if(actionType.value === 'add'){
    //新增
    const res = await addSetmeal(params)
    // console.log(res)
    if(res.data.code === 1){
      ElMessage.success("添加套餐零食成功")
      console.log(!st)
      if (!st) {
        router.push('/setmeal')
      }else{
        ruleForm.value ={
          name: '',
          categoryId: '',
          price: '',
          image: '',
          description: '',
          status: true,
        }
        imageUrl.value = ''
       snacksTable.value = []
       checkList.value =  []
      }
    }
  }else{
    //修改
    // console.log(params)
    const res  = await editSetmeal(params)
    console.log(res)
    if(res.data.code === 1 ){
      ElMessage.success('修改套餐成功！')
      router.push('/setmeal')
    }
    

  }
 }
}

</script>

<template>
    <div class="addBrand-container">
      <div style="display: flex; align-items: center;">
      <el-icon style="margin-right: 10px; margin-bottom: 20px">
        <Back />
      </el-icon>
      <el-button type="text" @click="() => router.push('/setmeal')" style="margin-bottom: 20px;">返回
      </el-button>

    </div>
      <div class="container">
        <el-form ref="formRef" :model="ruleForm" :rules="rules">
          <div class="life">
          <el-form-item label="套餐名称:" 
                        prop="name">
            <el-input v-model="ruleForm.name"
                      placeholder="请填写套餐名称"
                      maxlength="14" />
          </el-form-item>

          <el-form-item label="套餐分类:"
                        prop="categoryId">
            <el-select v-model="ruleForm.categoryId"
                       placeholder="请选择套餐分类"
                       @change="$forceUpdate()">
              <el-option  v-for="(item, index) in setMealList"
                         :key="index"
                         :label="item.name"
                         :value="item.id"
                         />
                         
            </el-select>
          </el-form-item>
        </div>
        
        <div>
          <el-form-item label="套餐价格:"
                        prop="price">
            <el-input v-model="ruleForm.price"
                      placeholder="请设置套餐价格" />
          </el-form-item>
        </div>

        <div>
          <el-form-item label="套餐零食:"
                        required>
                        <el-form-item>
                          <div class="addSnacks">
                            <span v-if="snacksTable.length == 0"
                      class="addBut"
                      @click="openAddSnacks('new')">
                  + 添加零食</span>

                  <div v-if="snacksTable.length != 0"
                     class="content">
                  <div class="addBut"
                       style="margin-bottom: 20px"
                       @click="openAddSnacks('change')">
                    + 添加零食
                  </div>
                  <div class="table">
                    <el-table :data="snacksTable"
                              style="width: 100%">
                      <el-table-column prop="name"
                                       label="名称"
                                       width="180"
                                       align="center" />
                      <el-table-column prop="price"
                                       label="原价"
                                       width="180"
                                       align="center">
                        <template #default="scope">
                          {{ (Number(scope.row.price).toFixed(2) * 100) / 100 }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="address"
                                       label="份数"
                                       align="center">
                        <template #default="scope">
                          <el-input-number v-model="scope.row.copies"
                                           size="small"
                                           :min="1"
                                           :max="99"
                                           label="描述文字" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="address"
                                       label="操作"
                                       width="180px;"
                                       align="center">
                        <template #default="scope">
                          <el-button type="text"
                                     size="small"
                                     class="delBut non"
                                     @click="delSnacksHandle(scope.$index)">
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>

                          </div>
                        </el-form-item>            
          </el-form-item>

        </div>

        <div>
          <el-form-item label="零食图片:" prop="image">
            <ImgUpload :prop-image-url="imageUrl" @imageChange="imageChange">
              图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
            </ImgUpload>

          </el-form-item>
        </div>


        <div class="address">
          <el-form-item label="套餐描述:">
            <el-input v-model="ruleForm.description"
                      type="textarea"
                      :rows="3"
                      maxlength="200"
                      placeholder="套餐描述，最长200字" />
          </el-form-item>
        </div>

        <div class="subBox address">
          <el-form-item>
            <el-button @click="() => $router.back()">
              取消
            </el-button>
            <el-button type="primary"
                       :class="{ continue: actionType === 'add' }"
                       @click="submitForm('ruleForm')">
              保存
            </el-button>
            <el-button v-if="actionType == 'add'"
                       type="primary"
                       @click="submitForm('ruleForm', 'goAnd')">
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>

        </el-form>  
      </div>
<!-- 弹窗 -->
    <el-drawer v-model="drawer" title="新增零食套餐" class="addDishList"  size="60%" :before-close="handleClose">
    
      <addSnacks 
      
              v-model="drawer"
               ref="addsnacks"
               :check-list="checkList"
               :seach-key="seachKey"
               :snacks-list="snackshList"
               @checkList="getCheckList"
      /> 

    

    <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary"
                   @click="addTableList">添 加</el-button>
      </span>
  </el-drawer>

    </div>
</template>

<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 10px;
    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      min-height: 500px;

      .life{
        display: flex;
        justify-content: flex-start;
        .el-form-item {
        margin-right: 60px; /* 可以调整间距 */
}
      }
      .subBox {
        padding-top: 30px;
        text-align: center;
      }

      .address {
        width: 50%;
      }
      .addSnacks {
        width: 777px;
        .addBut {
          background: #00b7ff;
          display: inline-block;
          padding: 0px 20px;
          border-radius: 3px;
          line-height: 40px;
          cursor: pointer;
          border-radius: 4px;
          color: #333333;
          font-weight: 500;
        }
      }
      
    }

    .idNumber {
      margin-bottom: 39px;
    }

    .el-form-item {
      margin-bottom: 29px;
    }
    .el-input {
      width: 293px;
    }
  }

}
</style>